package com.model.common.base.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;

import com.gyf.barlibrary.ImmersionBar;
import com.model.common.R;
import com.model.common.utils.always.StringUtils;

import org.greenrobot.eventbus.EventBus;

/**
 * Create by Carson on 2021/12/22.
 * BaseAppCompatActivity
 */
public abstract class BaseAppCompatActivity<VB extends ViewBinding> extends AppCompatActivity
        implements View.OnClickListener {

    public static final int NON_CODE = -1;

    /*获取屏幕信息*/
    protected int mScreenWidth = 0;
    protected int mScreenHeight = 0;
    protected float mScreenDensity = 0.0f;

    protected Context mContext = null;
    protected ImmersionBar mImmersionBar;
    protected VB binding;
    protected Dialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //传参
        Bundle extras = getIntent().getExtras();
        if (null != extras) {
            getBundleExtras(extras);
        }

        //注册EventBus
        if (isBindEventBusHere()) {
            EventBus.getDefault().register(this);
            Log.e("eventBus", "register");
        }

        mContext = this;

        // 加入到Activity栈
        BaseAppManager.getInstance().addActivity(this);

        /* 获取屏幕信息 */
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        mScreenDensity = displayMetrics.density;
        mScreenHeight = displayMetrics.heightPixels;
        mScreenWidth = displayMetrics.widthPixels;
        if (isImmersionBarEnabled()) {
            initImmersionBar();
        }
        binding = getViewBinding();
        setContentView(binding.getRoot());

        if (hasTitleBar()) {
            setCustomTitle(getTitle());
            onTitleBarBackClick();
        }
        initViewsAndEvents();
        addListener();
    }

    protected void initImmersionBar() {
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.init();
        if (ImmersionBar.isSupportStatusBarDarkFont())
            mImmersionBar.statusBarDarkFont(true).keyboardEnable(true).init();
    }

    //绑定标题栏
    protected boolean hasTitleBar() {
        return findViewById(R.id.title_bar) != null;
    }

    //设置标题title
    protected void setCustomTitle(CharSequence title) {
        if (hasTitleBar()) {
            TextView titleView = findViewById(R.id.title_name);
            if (titleView != null) {
                titleView.setText(title);
                setTitle("");
            }
        }
    }

    //获取标题栏返回键
    protected void onTitleBarBackClick() {
        if (hasTitleBar()) {
            ImageButton backView = findViewById(R.id.actionbar_back);
            if (backView != null) {
                backView.setOnClickListener(v -> finish());
            }
        }
    }

    public synchronized void hideLoading() {
        Log.e("loadingDialog", ">>>>>>  hideLoading");
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    public synchronized void showLoading(String message) {
        Log.e("loadingDialog", ">>>>>>  showLoading");
        if (loadingDialog == null) {
            loadingDialog = new Dialog(this, R.style.NoTitleDialogStyle);
            loadingDialog.setContentView(R.layout.loading_view);
            loadingDialog.setCanceledOnTouchOutside(false);
        }
        loadingDialog.show();
        TextView loadingMessage = loadingDialog.findViewById(R.id.tv_loading_message);
        if (message == null || StringUtils.isEmpty(message)) {
            loadingMessage.setVisibility(View.GONE);
        } else {
            loadingMessage.setVisibility(View.VISIBLE);
            loadingMessage.setText(message);
        }
    }

    @Override
    protected void onPause() {
        hideLoading();
        super.onPause();
    }

    /**
     * 是否可以使用沉浸式
     */
    protected boolean isImmersionBarEnabled() {
        return true;
    }

    /**
     * bind layout resource file
     */
    protected abstract VB getViewBinding();

    /**
     * init activity view and bind event
     */
    protected abstract void initViewsAndEvents();

    /**
     * 是否注册EventBus
     */
    protected boolean isBindEventBusHere() {
        return false;
    }

    protected void getBundleExtras(Bundle extras) {
    }

    /**
     * 给 View 控件添加点击事件监听器
     */
    protected void addListener() {
    }

    /**
     * view的点击事件
     * 屏蔽快速点击而引发的问题
     */
    protected void onWidgetClick(View view) {
    }

    private long lastTime = 0L;
    private View currentView = null;

    @Override
    public void onClick(View view) {
        long nowTime = System.currentTimeMillis();
        if (nowTime - lastTime > 1000L || view.getId() == currentView.getId()) {
            lastTime = nowTime;
            currentView = view;
            onWidgetClick(view);
        }
    }

    /**
     * startActivity
     *
     * @param clazz target Activity
     */
    protected void go(Class<? extends Activity> clazz) {
        _goActivity(clazz, null, NON_CODE, false);
    }

    /**
     * startActivity with bundle
     *
     * @param clazz target Activity
     */
    protected void go(Class<? extends Activity> clazz, Bundle bundle) {
        _goActivity(clazz, bundle, NON_CODE, false);
    }

    /**
     * startActivity then finish this
     *
     * @param clazz target Activity
     */
    protected void goAndFinish(Class<? extends Activity> clazz) {
        _goActivity(clazz, null, NON_CODE, true);
    }

    /**
     * startActivity with bundle and then finish this
     *
     * @param clazz  target Activity
     * @param bundle bundle extra
     */
    protected void goAndFinish(Class<? extends Activity> clazz, Bundle bundle) {
        _goActivity(clazz, bundle, NON_CODE, true);
    }

    /**
     * startActivityForResult
     */
    protected void goForResult(Class<? extends Activity> clazz, int requestCode) {
        _goActivity(clazz, null, requestCode, false);
    }

    /**
     * startActivityForResult with bundle
     */
    protected void goForResult(Class<? extends Activity> clazz, Bundle bundle, int requestCode) {
        _goActivity(clazz, bundle, requestCode, false);
    }

    /**
     * startActivityForResult then finish this
     */
    protected void goForResultAndFinish(Class<? extends Activity> clazz, int requestCode) {
        _goActivity(clazz, null, requestCode, true);
    }

    /**
     * startActivityForResult with bundle and then finish this
     */
    protected void goForResultAndFinish(Class<? extends Activity> clazz, Bundle bundle, int requestCode) {
        _goActivity(clazz, bundle, requestCode, true);
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
    }

    @Override
    public void finish() {
        super.finish();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
        }
        BaseAppManager.getInstance().removeActivity(this);
    }

    @Override
    protected void onDestroy() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
        if (isBindEventBusHere()) {
            EventBus.getDefault().unregister(this);
            Log.e("eventBus", "unregister");
        }
        if (mImmersionBar != null) {
            mImmersionBar.destroy();
        }
        BaseAppManager.getInstance().removeActivity(this);
        binding = null;
        super.onDestroy();
    }

    /**
     * Activity 跳转
     *
     * @param clazz  目标activity
     * @param bundle 传递参数
     * @param finish 是否结束当前activity
     */
    private void _goActivity(Class<? extends Activity> clazz, Bundle bundle, int requestCode, boolean finish) {
        if (null == clazz) {
            throw new IllegalArgumentException("you must pass a target activity where to go.");
        }
        Intent intent = new Intent(this, clazz);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        if (requestCode > NON_CODE) {
            startActivityForResult(intent, requestCode);
        } else {
            startActivity(intent);
        }
        if (finish) {
            finish();
        }
    }
}
